package com.basics.framework.web.domain;


import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;

import java.io.Serializable;
import java.util.Iterator;
import java.util.List;

@ApiModel(
        value = "返回值",
        description = "返回值数据"
)
public class ApiResult<T> implements Serializable {
    private static final long serialVersionUID = -5337701537489516223L;
    @ApiModelProperty("提示语")
    private String msg;
    @ApiModelProperty("错误码(1:失败 0:成功 2:登录超时 500:接口异常)")
    private Integer code;
    @ApiModelProperty("数据")
    private T data;

    public ApiResult() {
    }

    public ApiResult(String msg, Integer code, T data) {
        this.msg = msg;
        this.code = code;
        this.data = data;
    }

    public static <T> ApiResult<T> error(String msg) {
        return new ApiResult(msg, 1, new JSONObject());
    }

    public static <T> ApiResult<T> errorToken() {
        return new ApiResult("token失效", 2, new JSONObject());
    }

    public static <T> ApiResult<T> error(int code, String msg, T data) {
        return new ApiResult(msg, code, data);
    }

    public static <T> ApiResult<T> success(String msg) {
        return new ApiResult(msg, 0, new JSONObject());
    }

    public static <T> ApiResult<T> success() {
        return success("操作成功");
    }

    public static <T> ApiResult<T> success(T data) {
        ApiResult<T> json = success();
        if (null != data) {
            json.setData(data);
        }

        return json;
    }

    public ApiResult<T> onBindingError(List<ObjectError> errors) {
        return new ApiResult(praseErrorMessage(errors), 500, new JSONObject());
    }

    public static String praseErrorMessage(List<ObjectError> errors) {
        StringBuffer stringBuffer = new StringBuffer();
        Iterator var2 = errors.iterator();

        while(var2.hasNext()) {
            ObjectError error = (ObjectError)var2.next();
            if (error instanceof FieldError) {
                FieldError fieldError = (FieldError)error;
                stringBuffer.append(fieldError.getDefaultMessage());
                stringBuffer.append(",");
            }
        }

        return stringBuffer.toString().substring(0, stringBuffer.toString().length() - 1);
    }

    public String getMsg() {
        return this.msg;
    }

    public Integer getCode() {
        return this.code;
    }

    public T getData() {
        return this.data;
    }

    public void setMsg(final String msg) {
        this.msg = msg;
    }

    public void setCode(final Integer code) {
        this.code = code;
    }

    public void setData(final T data) {
        this.data = data;
    }

}
